#pragma once

#include "Thread.hpp"
#include "Cond.hpp"
#include "Mutex.hpp"
#include "Log.hpp"
#include <vector>
#include <queue>

namespace ThreadPoolModule
{
    using namespace ThreadModule;
    using namespace CondModule;
    using namespace MutexModule;
    using namespace LogModule;

    template <typename T>
    class ThreadPool
    {
        static const int gnum = 15;

    private:
        void TaskHandler()
        {
            char name[64];
            pthread_getname_np(pthread_self(), name, sizeof(name));
            while (true)
            {
                T t;
                {
                    LockGuard guard(_mutex);
                    // 任务队列本身没有任务，需要保证_isrunning
                    while (_taskq.empty() && _isrunning)
                    {
                        _sleepernum++;
                        _cond.Wait(_mutex);
                        _sleepernum--;
                    }
                    // 线程池暂停必须将队列中的任务处理完成
                    if (!_isrunning && _taskq.empty())
                    {
                        LOG(LogLevel::INFO) << name << " 线程退出，线程池暂停 && 任务队列为空";
                        break;
                    }
                    t = _taskq.front();
                    _taskq.pop();
                }

                std::cout << "准备运行任务  线程ID" << pthread_self() << std::endl;
                std::cout << "----------------------" << std::endl;
                t();
            }
        }

        // 唤醒所有线程
        void WakeUpAllThreads()
        {
            LockGuard guard(_mutex);
            if (_sleepernum > 0)
            {
                LOG(LogLevel::INFO) << "唤醒所有线程";
                _cond.Broadcast();
            }
        }

        // 唤醒一个线程
        void WakeUpOneThread()
        {
            LOG(LogLevel::INFO) << "唤醒一个线程";
            _cond.Signal();
        }

        //  构造
        ThreadPool(int num = gnum)
            : _num(num), _isrunning(false), _sleepernum(0)
        {
            for (int i = 0; i < _num; i++)
            {
                _threads.emplace_back([this]()
                                      { TaskHandler(); });
            }
        }

        // 赋值拷贝禁用
        ThreadPool(const ThreadPool<T> &) = delete;
        ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

    public:
        // 获取单例
        static ThreadPool<T> *GetInstance()
        {
            if (_instance == nullptr)
            {
                LockGuard guard(_instanceMutex);
                LOG(LogLevel::INFO) << "获取线程池单例...";
                if (_instance == nullptr)
                {
                    LOG(LogLevel::INFO) << "首次创建程池单例...";
                    _instance = new ThreadPool<T>();
                    _instance->Start();
                }
            }
            return _instance;
        }
        // 启动线程池
        void Start()
        {
            if (_isrunning)
                return;
            LOG(LogLevel::INFO) << "Threadpool has been created successfully!";
            _isrunning = true;
            for (auto &thread : _threads)
            {
                thread.Start();
            }
        }

        // 暂停线程池
        void Stop()
        {
            if (!_isrunning)
                return;
            _isrunning = false;

            // 唤醒所有的线程
            WakeUpAllThreads();
        }

        // 等待线程池中的线程
        void Join()
        {
            for (auto &thread : _threads)
            {
                thread.Join();
                LOG(LogLevel::INFO) << thread.GetName() << "线程Join成功";
            }
        }

        // 向队列中添加任务
        bool Enqueue(const T &in)
        {
            if (_isrunning)
            {
                LockGuard guard(_mutex);
                _taskq.push(in);
                
               // if (_threads.size() - _sleepernum == 0)
               // {
                 //   std::cout << "唤醒一个线程" << std::endl;
                    WakeUpOneThread();
               // }
                return true;
            }
            return false;
        }

        // 析构
        ~ThreadPool() {}

    private:
        std::vector<Thread> _threads; // 线程池底层数据结构
        int _num;                     // 线程池中线程的个数
        std::queue<T> _taskq;         // 任务队列
        Cond _cond;
        Mutex _mutex;

        bool _isrunning; // 线程池是否运行

        size_t _sleepernum; // 正在条件变量下等待的线程个数

        static ThreadPool<T> *_instance; // 单例指针
        static Mutex _instanceMutex;     // 单例也是共享资源
    };

    template <typename T>
    ThreadPool<T> *ThreadPool<T>::_instance = nullptr;

    template <typename T>
    Mutex ThreadPool<T>::_instanceMutex;
}